package main

import (
	"fmt"
	"go_code/day15/database"
)

// 作家模型类
type Author struct {
	Id   uint
	Name string `gorm:"size:20"`
	// 创建一对多关系
	Article []Article `gorm:"foreignKey:AuthorId"`
}

func (a Author) TableName() string {
	return "author"
}

// 文章模型类
type Article struct {
	Id       uint
	Title    string `gorm:"size:100"`
	AuthorId uint
	Author   Author // 让文章的模型关联作家
}

func (a Article) TableName() string {
	return "article"
}

func main() {
	db := database.DB()
	// 迁移
	db.AutoMigrate(&Author{}, &Article{})
	/*
		// 插入数据
		a1 := Author{
			Name: "小明",
			Article: []Article{
				{Title: "2025中国经济这么干"},
				{Title: "中国对美反制措施，即刻生效！"},
			},
		}
		err := db.Create(&a1).Error
		if err != nil {
			panic(err)
		}
		fmt.Println("插入成功")

		// 单独插入
		a2 := Author{
			Name: "小红",
		}
		err := db.Create(&a2).Error
		if err != nil {
			panic(err)
		}

		article := Article{
			Title:    "长安汽车重庆马拉松上的机器人选手",
			AuthorId: 2,
		}
		err := db.Create(&article).Error
		if err != nil {
			panic(err)
		}
	*/
	// 查询数据
	// var author Author
	// db.Preload("Article").Where("id = ?", 2).First(&author)
	// fmt.Println(author)

	var article Article
	db.Preload("Author").Where("id = ?", 3).First(&article)
	// fmt.Println(article)
	fmt.Printf("文章：%s  作家：%s \n", article.Title, article.Author.Name)

}
